<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 主体内容 -->
    <div class="flex min-h-screen">
      <!-- 右侧内容 -->
      <div class="w-full p-6">
        <!-- 统计卡片 -->
        <div class="grid grid-cols-3 gap-6 mb-6">
          <div class="bg-white p-6 rounded-lg shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-gray-500 text-sm mb-1">在研项目</div>
                <div class="text-2xl font-semibold">
                  {{ headerData.executingProjectCount }}
                </div>
              </div>
              <el-icon class="text-blue-500 text-3xl"><Loading /></el-icon>
            </div>
          </div>
          <div class="bg-white p-6 rounded-lg shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-gray-500 text-sm mb-1">项目总经费</div>
                <div class="text-2xl font-semibold">
                  {{ headerData.projectTotalFund }} 万
                </div>
              </div>
              <el-icon class="text-green-500 text-3xl"><Money /></el-icon>
            </div>
          </div>
          <div class="bg-white p-6 rounded-lg shadow-sm">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-gray-500 text-sm mb-1">经费使用率</div>
                <div class="text-2xl font-semibold">
                  <!-- 保留两位小数 -->
                  {{ headerData.usedExpensePercent.toFixed(2) }}%
                </div>
              </div>
              <el-icon class="text-orange-500 text-3xl"><PieChart /></el-icon>
            </div>
          </div>
        </div>

        <!-- 搜索和筛选区 -->
        <div class="bg-white p-6 rounded-lg shadow-sm mb-6">
          <div class="grid grid-cols-4 gap-6">
            <el-input
              v-model="queryParams.title"
              placeholder="搜索项目名称"
              class="w-full"
              :prefix-icon="Search"
            />
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              class="w-full"
            >
              <el-option label="全部状态" value="" />
              <el-option label="申请中" value="申请中" />
              <el-option label="评审中" value="评审中" />
              <el-option label="执行中" value="执行中" />
              <el-option label="验收中" value="验收中" />
              <el-option label="完成" value="完成" />
              <el-option label="驳回" value="驳回" />
            </el-select>
            <el-button
              type="primary"
              width="100px"
              class="!rounded-button whitespace-nowrap"
              @click="handleQuery"
            >
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
          </div>
        </div>

        <!-- 项目列表 -->
        <div class="bg-white rounded-lg shadow-sm">
          <el-table :data="executionsList" style="width: 100%">
            <el-table-column type="expand">
              <template #default="props">
                <div class="p-6">
                  <div class="grid grid-cols-2 gap-x-12 gap-y-4">
                    <div>
                      <div class="text-gray-500 mb-2">项目进度</div>
                      <el-progress :percentage="props.row.progress" />
                    </div>
                    <div>
                      <div class="text-gray-500 mb-2">经费使用</div>
                      <el-progress
                        :percentage="props.row.fundProjects.usedFundProgress"
                      />
                    </div>
                    <div>
                      <div class="text-gray-500 mb-2">最近更新</div>
                      <div>{{ props.row.updateTime }}</div>
                    </div>
                    <div>
                      <div class="text-gray-500 mb-2">项目周期</div>
                      <div>
                        <!-- 转换时间格式： -->
                        {{
                          new Date(
                            props.row.fundProjects.startDate
                          ).toLocaleDateString()
                        }}
                        至
                        {{
                          new Date(
                            props.row.fundProjects.deadline
                          ).toLocaleDateString()
                        }}
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="projectId" label="项目编号" />
            <el-table-column prop="fundProjects.title" label="项目名称">
            </el-table-column>
            <el-table-column prop="fundProjects.applicantName" label="申请人" />
            <el-table-column prop="fundProjects.budget" label="总经费">
              <template #default="{ row }">
                {{ row.fundProjects.budget }} 万元
              </template>
            </el-table-column>
            <el-table-column prop="usedFund" label="已用经费">
              <template #default="{ row }">
                {{ row.fundProjects.usedFund }} 万元
              </template>
            </el-table-column>
            <el-table-column prop="progress" label="项目进度">
              <template #default="{ row }">
                <el-progress :percentage="row.progress" />
              </template>
            </el-table-column>
            <el-table-column prop="progressStatus" label="执行状态">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.fundProjects.status === '申请中'
                      ? 'info'
                      : row.fundProjects.status === '评审中'
                      ? 'primary'
                      : row.fundProjects.status === '执行中'
                      ? 'primary'
                      : row.fundProjects.status === '验收中'
                      ? 'info'
                      : row.fundProjects.status === '完成'
                      ? 'success'
                      : row.fundProjects.status === '驳回'
                      ? 'danger'
                      : 'info'
                  "
                >
                  {{ row.fundProjects.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="300">
              <template #default="{ row }">
                <div class="flex space-x-2">
                  <el-button
                    :disabled="
                      row.fundProjects.status === '完成' ||
                      row.fundProjects.status === '撤题'
                    "
                    type="primary"
                    link
                    @click="updateProgress(row)"
                    >更新进度</el-button
                  >
                  <el-button
                    :disabled="
                      row.fundProjects.status === '完成' ||
                      row.fundProjects.status === '撤题'
                    "
                    type="primary"
                    link
                    @click="manageFunds(row)"
                    >经费管理</el-button
                  >
                  <el-button
                    :disabled="
                      row.fundProjects.status !== '驳回' &&
                      row.fundProjects.status !== '执行中'
                    "
                    type="warning"
                    link
                    @click="delayProject(row)"
                    >延期</el-button
                  >
                  <el-button
                    :disabled="row.fundProjects.status === '完成' || row.fundProjects.status === '撤题'"
                    type="danger"
                    link
                    @click="withdrawProject(row)"
                    >撤题</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex justify-end p-4">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              :total="total"
              :page-sizes="[100]"
              layout="total, sizes, prev, pager, next"
            />
          </div>
        </div>

        <!-- 更新进度对话框 -->
        <el-dialog
          v-model="showProgressDialog"
          title="更新项目进度"
          width="600px"
        >
          <el-form :model="progressForm" label-width="120px">
            <el-form-item label="当前进度" required>
              <el-slider v-model="progressForm.progress" :step="5" show-input />
            </el-form-item>
            <el-form-item label="相关文件">
              <!-- 上传文件 -->
              <file-upload
                :fileSize="10"
                v-model="progressForm.midTermReport"
              ></file-upload>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showProgressDialog = false">取消</el-button>
              <el-button
                type="primary"
                class="!rounded-button"
                @click="submitProgress"
              >
                确认
              </el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 经费管理对话框 -->
        <el-dialog v-model="showFundsDialog" title="经费使用管理" width="800px">
          <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
              <div class="text-lg font-medium">经费概览</div>
              <div class="flex space-x-4">
                <div class="text-gray-500">
                  总经费：<span class="text-black font-medium"
                    >{{ selectedProject.fundProjects.budget }} 万元</span
                  >
                </div>
                <div class="text-gray-500">
                  已用经费：<span class="text-black font-medium"
                    >{{ selectedProject.fundProjects.usedFund }} 万元</span
                  >
                </div>
                <div class="text-gray-500">
                  剩余经费：<span class="text-black font-medium"
                    >{{
                      selectedProject.fundProjects.budget -
                      selectedProject.fundProjects.usedFund
                    }}
                    万元</span
                  >
                </div>
              </div>
            </div>
            <el-progress
              :percentage="selectedProject.fundProjects.usedFundProgress"
            />
          </div>

          <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
              <div class="text-lg font-medium">经费使用记录</div>
              <el-button
                type="primary"
                class="!rounded-button"
                @click="showAddFundRecord = true"
              >
                <el-icon class="mr-1"><Plus /></el-icon>
                添加记录
              </el-button>
            </div>
            <el-table :data="fundProjectExpenses" style="width: 100%">
              <el-table-column
                prop="expenseDate"
                label="使用日期"
                width="120"
              />
              <el-table-column prop="expenseType" label="用途类型" width="120">
              </el-table-column>
              <el-table-column prop="description" label="用途说明" />
              <el-table-column
                prop="expenseAmount"
                label="金额(万元)"
                width="120"
              />
            </el-table>
          </div>
        </el-dialog>

        <el-dialog
          v-model="showAddFundRecord"
          title="添加经费记录"
          width="500px"
          append-to-body
        >
          <el-form :model="newFundRecord" label-width="100px">
            <el-form-item label="使用日期" required>
              <el-date-picker
                v-model="newFundRecord.expenseDate"
                type="date"
                placeholder="选择日期"
                class="w-full"
              />
            </el-form-item>
            <el-form-item label="用途类型" required>
              <el-select
                v-model="newFundRecord.expenseType"
                placeholder="选择用途类型"
                class="w-full"
              >
                <el-option label="设备购置" value="设备购置" />
                <el-option label="材料费" value="材料费" />
                <el-option label="差旅费" value="差旅费" />
                <el-option label="会议费" value="会议费" />
                <el-option label="劳务费" value="劳务费" />
              </el-select>
            </el-form-item>
            <el-form-item label="用途说明" required>
              <el-input
                v-model="newFundRecord.description"
                type="textarea"
                rows="3"
                placeholder="请详细说明经费用途"
              />
            </el-form-item>
            <el-form-item label="使用金额" required>
              <el-input-number
                v-model="newFundRecord.expenseAmount"
                :min="0"
                :max="selectedProject.totalFund - selectedProject.usedFund"
                :step="1"
                class="w-full"
                placeholder="请输入金额（万元）"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showAddFundRecord = false">取消</el-button>
              <el-button
                type="primary"
                class="!rounded-button"
                @click="submitFundRecord"
                >确定</el-button
              >
            </span>
          </template>
        </el-dialog>

        <el-dialog v-model="showDelayDialog" title="项目延期申请" width="500px">
          <el-form :model="delayForm" label-width="120px">
            <el-form-item label="当前截止日期" required>
              <div>
                {{ new Date(delayForm.currentDeadline).toLocaleDateString() }}
              </div>
            </el-form-item>
            <el-form-item label="延期至" required>
              <el-date-picker
                v-model="delayForm.newDeadline"
                type="date"
                placeholder="选择新的截止日期"
                class="w-full"
                :min-date="new Date()"
              />
            </el-form-item>
            <el-form-item label="延期原因" required>
              <el-input
                v-model="delayForm.delayReason"
                type="textarea"
                rows="3"
                placeholder="请详细说明延期原因"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showDelayDialog = false">取消</el-button>
              <el-button
                type="primary"
                class="!rounded-button"
                @click="submitDelay"
              >
                确认
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script setup name="Executions">
import {
  listExecutions,
  getExecutions,
  delExecutions,
  addExecutions,
  updateExecutions,
  applyDelay,
  applyWithdraw,
} from "@/api/project/execution.js"

import {
  addExpenses,
  delExpenses,
  getExpenses,
  listExpenses,
  updateExpenses,
} from "@/api/project/expense.js"

const { proxy } = getCurrentInstance()
import { getExecutionData } from "@/api/project/view.js"

const headerData = ref({})

const executionsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const showProgressDialog = ref(false)

const showFundsDialog = ref(false)
const showAddFundRecord = ref(false)
// 延期对话框显示控制
const showDelayDialog = ref(false)
const selectedProject = ref({})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    projectId: null,
    midTermReport: null,
    midTermDate: null,
    executionStatus: null,
    progress: null,
    remarks: null,
  },
  newFundRecord: {
    projectId: null,
    expenseAmount: null,
    expenseDate: null,
    expenseType: null,
    description: null,
  },
  rules: {
    projectId: [{ required: true, message: "项目ID不能为空", trigger: "blur" }],
    executionStatus: [
      { required: true, message: "执行状态不能为空", trigger: "change" },
    ],
    progress: [
      { required: true, message: "项目进度不能为空", trigger: "blur" },
    ],
    updateTime: [
      { required: true, message: "状态更新时间不能为空", trigger: "blur" },
    ],
  },
})

const { queryParams, form, rules, newFundRecord } = toRefs(data)

/** 查询项目执行记录列表 */
function getList() {
  loading.value = true
  listExecutions(queryParams.value).then((response) => {
    executionsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
  getExecutionData().then((response) => {
    headerData.value = response.data
  })
}
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  console.log("页码切换为:", val)
  // 确保在状态更新后再获取数据
  getList()
}

function handleSizeChange(val) {
  queryParams.value.pageSize = val
  queryParams.value.pageNum = 1
  console.log("每页条数切换为:", val)
  // 确保在状态更新后再获取数据
  getList()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    midTermReport: null,
    midTermDate: null,
    executionStatus: null,
    progress: null,
    remarks: null,
    updateTime: null,
  }
  proxy.resetForm("executionsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

const fundProjectExpenses = ref([])
const manageFunds = (row) => {
  selectedProject.value = row
  fundProjectExpenses.value = row.fundProjectExpenses
  showFundsDialog.value = true
  newFundRecord.value.projectId = row.projectId
}

const progressForm = ref({
  id: null,
  progress: 0,
  midTermReport: null,
})

// 延期表单数据
const delayForm = ref({
  id: null,
  projectId: null,
  currentDeadline: null,
  newDeadline: null,
  delayReason: null,
})

const updateProgress = (row) => {
  progressForm.value = row
  progressForm.value.id = row.id
  console.log(progressForm)
  showProgressDialog.value = true
}
const submitProgress = () => {
  console.log("提交进度更新", progressForm.value)
  updateExecutions(progressForm.value).then((response) => {
    proxy.$modal.msgSuccess("修改成功")
    showProgressDialog.value = false
    getList()
  })
}

const withdrawProject = (row) => {
  proxy.$modal
    .confirm(
      '是否确认撤回项目"' + row.fundProjects.title + '"？撤回后将无法继续执行。'
    )
    .then(function () {
      applyWithdraw({ projectId: row.projectId }).then((response) => {
        proxy.$modal.msgSuccess("撤回成功")
        getList()
      })
    })
    .catch(() => {})
}

/** 查询项目费用记录列表 */
function getFundList() {
  loading.value = true
  getExecutions(newFundRecord.value.projectId).then((response) => {
    fundProjectExpenses.value = response.data.fundProjectExpensesList
    selectedProject.fundProjects.usedFund = response.data.usedFund
    selectedProject.fundProjects.usedFundProgress =
      response.data.usedFundProgress
    total.value = response.total
    loading.value = false
  })
}

/** 提交按钮 */
function submitFundRecord() {
  addExpenses(newFundRecord.value).then((response) => {
    proxy.$modal.msgSuccess("新增成功")
    showAddFundRecord.value = false
    getFundList()
    getList()
  })
}

const delayProject = (row) => {
  delayForm.value.id = row.id
  delayForm.value.projectId = row.projectId
  delayForm.value.currentDeadline = row.fundProjects.deadline
  delayForm.value.newDeadline = null
  showDelayDialog.value = true
}

const submitDelay = () => {
  if (!delayForm.value.newDeadline) {
    proxy.$modal.msgError("请选择新的截止日期")
    return
  }

  // 确保新日期晚于当前日期
  if (
    new Date(delayForm.value.newDeadline) <=
    new Date(delayForm.value.currentDeadline)
  ) {
    proxy.$modal.msgError("新截止日期必须晚于当前截止日期")
    return
  }
  // 更新项目信息，包含延期信息
  applyDelay(delayForm.value).then((response) => {
    proxy.$modal.msgSuccess("延期申请提交成功")
    showDelayDialog.value = false
    getList()
  })
}

getList()
</script>
<style scoped>
.el-menu {
  border-right: none;
}
:deep(.el-upload-dragger) {
  width: 100%;
}
:deep(.el-input-number .el-input__wrapper) {
  padding-left: 11px;
  padding-right: 11px;
}
:deep(.el-dialog__body) {
  padding: 20px 40px;
}
:deep(.el-progress-bar__outer) {
  background-color: #f0f2f5;
}
:deep(.el-slider__runway) {
  margin: 15px 0;
}
:deep(.el-table__expanded-cell) {
  padding: 0 !important;
}
</style>

